// pages/chooseCommunity/chooseCommunity.js
import api from "../../config/api";
import request from "../../utils/request";
import { getXsScreen, jump, getStorage } from "../../utils/utils";
import {
  getUserLocation,
  getUserPermissions,
  shareOptions,
} from '../../utils/access'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showList:true, // 是否显示推荐列表
    inputValue:'',
    cityName: "郑州市",
    communityList: [],
    showText:'取消',
    customItem:'',

    regionValue:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // wx.setNavigationBarColor({
    //   backgroundColor: '#000',
    //   // frontColor: 'frontColor',
    // })
    this.getSwitch()
    
    const { province,  city, direct  } = getStorage('addressInfo')
    if(province){
      this.setData({
        regionValue:[province, city, direct]
      })
    }
  },
  getSwitch: async function(){
    const res = await request.get('getSwitchData',{
      switchType:1
    })
    if(res.httpStatus===200&&res.data[0].miniAppSwitch===1){
      this.setData({
        showList:true
      })
      this.recommandCommunity()
    }else{
      this.setData({
        showList:false
      })
    }
  },
  bindRegionChange:function(e){
    console.log('bindRegionChange',e.detail);
    const {code} = e.detail
    // 确认添加，调用接口添加小区
    this.addCustomizedCommunity(code)

  },
  // 点击创建并认证
  clickText:function(){
    // const {regionValue} = this.data
    // if(regionValue.length===0){
    //   // 判断定位权限是否打开
    //   if (!getUserLocation()) {
    //     getUserPermissions('userLocation', (res) => {
    //       if (res) {
    //         console.log('定位权限是否打开',res);
    //         const {province,  city, direct} = res
    //         if(province){
    //           this.setData({
    //             regionValue:[province, city, direct]
    //           })
    //         }
    //       }
    //     })
    //     return
    //   }
    // }
  },
  // 清除输入框
  cleanInputValue(){
    const {showList} = this.data
		this.setData({
			inputValue: '',
    });
    if(showList){
      this.recommandCommunity()
    }
  },
	bindInputValue(e) {
    // \a-zA-Z 汉字 \u4E00-\u9FA5 英文 \d 数字 #- #和-
    var inputName = e.detail.value.replace(/[^\a-zA-Z\u4E00-\u9FA5\d#-]/g,'')

    console.log('isNaN(inputValue/2)',isNaN(inputName/2)); 
    console.log('isNaN(inputValue/2)',(inputName.length>0 && isNaN(inputName/2)))

		this.setData({
			inputValue: inputName,
    });
    // 调用接口请求小区列表
		this.getCommunityList(inputName);
	},

  getCommunityList:function(name){
    if(name.length>0){
      // 搜索
      this.getCommunityListFromServer(name)
    }else{
      // 可能在找的小区
      this.recommandCommunity()
    }
  },

  async recommandCommunity(){
    const {data} = await request.get(api.recommendCommunityNew)
    if(data && data.length>0){
      this.setData({
        communityList: data
      })
    }
  },

  async getCommunityListFromServer(name){
    const {data} = await request.get(api.chooseCommunity,{
      'communityName': name
    })
    console.log(data,'选择小区后返回的数据')
    this.setData({
      communityList: data,
      showText: (name.length>0 && data.length==0 && isNaN(name/2))?'确认':'取消'
    })


  },

  // 添加自定义小区
  async addCustomizedCommunity(code){
    const res = await request.post(api.addCustomizedCommunity,{
      'communityName': this.data.inputValue,
      'provinceId':code[0],
      'cityId':code[1],
      'areaId':code[2],
    })
    if (res.httpStatus == 200) {
      // 添加自定义小区成功
      this.backWithCommunity(res.data)
    }else{
      wx.showToast({
        title: '添加失败',
        icon: 'error'
      })
    }
  },

  communityItemTap:function(e){
    var community = e.currentTarget.dataset.community
    this.backWithCommunity(community)
  },

  backWithCommunity(community){
    if (this.loading) return
    this.loading = true
    console.log(community,'========')
   let pages = getCurrentPages();
   let prePage = pages[pages.length - 2]
   if (prePage.route === 'pages/residenceCertification/residenceCertification') {
      prePage.setData({
        communityIndex: null,
        communityCode: community.communityCode,
        communitySelect: community,
        buildingText: '',
        unitText: '',
        floorText: '',
        houseNoText: '',
     })
     prePage.getBuildInfo(community.communityCode)
   } else {
    prePage.setData({
      selected_community: community.communityName,
      pcode: community.provinceCode,
      pname: community.provinceName,
      location: community.location,
      name: community.communityName,
      citycode: community.cityCode,
      cityname: community.cityName,
      adcode: community.areaCode,
      adname: community.areaName,
      address: community.address,
      communityCode: community.communityCode,
      type:community.type,
      building: '',
      unit: '',
      floor: '',
      room: '',
      selected_room: ''
     })
   }
   

   wx.navigateBack({
     delta: 1,
     success: () => {
      this.loading = false
     }
   })
  },

  // cancelFind:function(){
  //   const {showText} = this.data
  //   if(showText==='确认'){
  //     // 确认添加，调用接口添加小区
  //     this.addCustomizedCommunity()
  //   }else{
  //     // 取消输入
  //     this.setData({
  //       inputValue: '',
  //     })
  //     this.recommandCommunity()
  //   }
  // },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {
    return shareOptions('default',e)
  }
})